package com.zjdiepu.www.manage.api.base;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Id;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.lang.ZNode;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.ibiz.base.ISysRoleApplicationService;
import com.zjdiepu.www.ibiz.base.ISysRoleService;
import com.zjdiepu.www.ibiz.base.ISysUserRoleService;
import com.zjdiepu.www.ibiz.base.ISysUserService;
import com.zjdiepu.www.ibiz.system.ISysAppRoleMenuService;
import com.zjdiepu.www.model.base.dto.SysRole;
import com.zjdiepu.www.model.base.dto.SysRoleApplication;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.ext.SysRoleExt;
import com.zjdiepu.www.model.base.response.NoticeUsersResponse;
import com.zjdiepu.www.model.system.dto.SysAppRoleMenu;

/**
* 所属公司：稻普控股集团
* 项目名称：dpqc-parent-manager-home   
* 类名称：SysRoleController   
* 类描述：  角色接口 
* 创建人：zhangpp
* 创建时间：2017年4月7日 下午12:01:58   
* 修改人：zhangpp
* 修改时间：2017年4月7日 下午12:01:58   
* 修改备注：   
* @version V1.0
 */
@RestController
@RequestMapping(value = "role")
public class SysRoleController extends BaseController {

	@Autowired
	private ISysRoleService sysRoleService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysRoleApplicationService sysRoleApplicationService;
	@Autowired
	private ISysAppRoleMenuService sysAppRoleMenuService;
	
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getNoticeUsers  <br/>
	 * @Description: 获取角色下通知的人 <br/>
	 * @param roleExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getNoticeUsers", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getNoticeUsers(String roleId) {
		if(StringUtils.isBlank(roleId)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY.getCode(), "必须参数角色ID为空");
		}
		String[] roleIds = roleId.split(",");
		List<NoticeUsersResponse> responses = new ArrayList<NoticeUsersResponse>();
		for(String roleId_ : roleIds) {
			NoticeUsersResponse response = new NoticeUsersResponse();
			SysRole sysRole = sysRoleService.selectById(roleId_);
			response.setRoleId(roleId_);
			
			response.setSysRole(sysRole);
			
			List<SysUser> sysUsers = sysRoleService.selectByRoleId(roleId_);
			response.setSysUsers(sysUsers);
			responses.add(response);
		}
		return ApiResponse.success(responses);
	}
	
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getEnableList  <br/>
	 * @Description: 角色列表 <br/>
	 * @param roleExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getEnableList", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getEnableList(@ModelAttribute SysRoleExt roleExt) {
		roleExt.setBaseWhere();
		roleExt.withOutPage();
		List<SysRole> roles = sysRoleService.selectByExt(roleExt);
		return ApiResponse.success(roles);
	}

	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getList  <br/>
	 * @Description: 角色列表 <br/>
	 * @param roleExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getList", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getList(@ModelAttribute SysRoleExt roleExt) {
		roleExt.notDeleted();
		PageVo page = getPage(roleExt);
		int records = sysRoleService.countByExt(roleExt);
		page.setRecords(records);
		if(records > 0){
			List<SysRole> roles = sysRoleService.selectByExt(roleExt);
			page.setRows(roles);
		} else {
			page.setRows(CollectionInitUtil.emptyList());
		}
		return ApiResponse.success(page);
	}

	/**
	 * @author xiongxiaotun <br/>
	 * @Title: queryOne  <br/>
	 * @Description: 角色详情 <br/>
	 * @param id
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value = "getById", method = RequestMethod.POST)
	public ApiResponse queryOne(String id) {
		if(StringUtils.isBlank(id)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY.getCode(), "请选择角色");
		}
		SysRole role = sysRoleService.selectById(id);
		if(null == role) {
			return ApiResponse.fail(ResultFlagType.MISSING.getCode(), "角色不存在");
		}
		return ApiResponse.success(role);
	}

	/**
	 * 添加角色
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "add" }, method = { RequestMethod.POST })
	public ApiResponse add(@Validated(Add.class) SysRole role) {
		AbstractSysUser currentUser = getCurrentUser();
		
		SysRole sysRole = new SysRole();
		sysRole.notDeleted();
		sysRole.setRoleName(role.getRoleName());
		boolean repeatName = sysRoleService.repeat(sysRole);
		if(repeatName) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "角色名称重复");
		}
		sysRole.setRoleName(null);
		sysRole.setRoleCode(role.getRoleCode());
		boolean repeatCode = sysRoleService.repeat(sysRole);
		if(repeatCode) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "角色编码重复");
		}
		
		role.setModifierName(currentUser.getName());
		role.setModifier(currentUser.getId());
		sysRoleService.saveUpdateAndDelete(role, OperateType.add);
		return ApiResponse.success(true);
	}
	
	/**
	 * 修改角色
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "modify" }, method = { RequestMethod.POST })
	public ApiResponse modify(@Validated(Update.class)  SysRole role) {
		AbstractSysUser currentUser = getCurrentUser();
		
		SysRole sysRole = new SysRole();
		sysRole.notDeleted();
		sysRole.setId(role.getId());
		sysRole.setRoleName(role.getRoleName());
		boolean repeatName = sysRoleService.repeat(sysRole);
		if(repeatName) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "角色名称重复");
		}
		sysRole.setRoleName(null);
		sysRole.setRoleCode(role.getRoleCode());
		boolean repeatCode = sysRoleService.repeat(sysRole);
		if(repeatCode) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "角色编码重复");
		}
		
		role.setModifierName(currentUser.getName());
		role.setModifier(currentUser.getId());
		sysRoleService.saveUpdateAndDelete(role, OperateType.edit);
		return ApiResponse.success(true);
	}


	/**
	 * 角色删除
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "del" }, method = { RequestMethod.POST })
	public ApiResponse del(@Validated(Id.class) SysRole role) {
		AbstractSysUser currentUser = getCurrentUser();
		boolean disableSuper = false;
		boolean success = false;
		for(String roleId : role.getId().split(",")) {
			if(StringUtils.isBlank(roleId)) {
				continue;
			}
			if(isSuper(roleId)) { //超级管理员权限角色不能修改
				disableSuper = true;
				continue;
			}
			SysRole role_ = new SysRole();
			role_.setId(roleId);
			role_.setModifierName(currentUser.getName());
			role_.setModifier(currentUser.getId());
			success = true;
			sysRoleService.saveUpdateAndDelete(role_, OperateType.delete);
		}
		if(disableSuper && !success) {
			return ApiResponse.fail(ResultFlagType.BAN_SUPER_ADMIN_ROLE);
		}
		return ApiResponse.success(true);
	}
	
	/**
	 * 角色树形结构
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param roleExt
	 * @return
	 */
	@RequestMapping(value = { "queryTree" }, method = { RequestMethod.POST })
	public ApiResponse queryTree(String userId) {
		if(StringUtils.isBlank(userId)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY.getCode(), "请选择角色");
		}
		List<SysRole> sysRoles = sysRoleService.selectByUserId(null);
		
		List<SysRole> userRoles = sysRoleService.selectByUserId(userId);
		
		final Set<String> hasRoles = CollectionUtils.isEmpty(userRoles) ? new HashSet<>() :userRoles.stream().map(userRole -> userRole.getId()).collect(Collectors.toSet());
		
		List<ZNode>  znodes = new ArrayList<ZNode>();
		String uuid = UUIDFactory.getUUID();
		znodes.add(new ZNode(uuid, "0", "稻普控股集团", true, false));
		if(CollectionUtils.isNotEmpty(sysRoles)) {
			znodes.addAll(sysRoles.stream().map(role -> new ZNode(role.getId(), uuid, role.getRoleName(), true, hasRoles.contains(role.getId()))).collect(Collectors.toList()));
		}
		return ApiResponse.success(znodes);
	}
	
	/**
	 * 分配APP菜单
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param roleExt
	 * @return
	 */
	@RequestMapping(value = { "appAllot" }, method = { RequestMethod.POST })
	public ApiResponse appAllot(@Validated(Add.class) SysAppRoleMenu sysAppRoleMenu) {
		AbstractSysUser currentUser = getCurrentUser();
		String roleIds = sysAppRoleMenu.getRoleId();
		String appMenuIds = sysAppRoleMenu.getAppMenuId();
		String appMenuCodes = sysAppRoleMenu.getAppMenuCode();
		boolean disableSuper = false;
		boolean success = false;
		String[] roleIds_ = roleIds.split(","); 
		String[] appMenuIds_ = appMenuIds.split(",");
		String[] appMenuCodes_ = appMenuCodes.split(","); 
		//添加当前权限
		List<SysAppRoleMenu> sysAppRoleMenus = new ArrayList<SysAppRoleMenu>();
		for(int i = 0; i <  roleIds_.length; i++) {
			String roleId = roleIds_[i];
			if(isSuper(roleId)) { //超级管理员权限角色不能修改
				disableSuper = true;
				continue;
			}
			//删除老权限
			SysAppRoleMenu sysAppRoleMenuDel_ = new SysAppRoleMenu();
			sysAppRoleMenuDel_.setRoleId(roleId);
			sysAppRoleMenuService.deletedRefined(sysAppRoleMenuDel_);
			
			for(int j = 0; j < appMenuIds_.length; j++) {
				String appMenuId = appMenuIds_[j];
				String appMenuCode = appMenuCodes_[j];
				if(StringUtils.isBlank(appMenuId)) {
					continue;
				}
				SysAppRoleMenu sysAppRoleMenu_ = new SysAppRoleMenu();
				sysAppRoleMenu_.initInsertData(currentUser.getId(), currentUser.getName());
				sysAppRoleMenu_.setRoleId(roleId);
				sysAppRoleMenu_.setAppMenuId(appMenuId);
				sysAppRoleMenu_.setAppMenuCode(appMenuCode);
				sysAppRoleMenus.add(sysAppRoleMenu_);
				success = true;
			}
		}
		if(disableSuper && !success) {
			return ApiResponse.fail(ResultFlagType.BAN_SUPER_ADMIN_ROLE);
		}
		sysAppRoleMenuService.insertBatch(sysAppRoleMenus);
		return ApiResponse.success(true);
	}
	
	/**
	 * 分配权限
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param roleExt
	 * @return
	 */
	@RequestMapping(value = { "allot" }, method = { RequestMethod.POST })
	public ApiResponse allot(@Validated(Add.class) SysRoleApplication sysRoleApplication) {
		
		String roleIds = sysRoleApplication.getRoleId();
		String functionIds = sysRoleApplication.getFunctionId();
		boolean disableSuper = false;
		boolean success = false;
		String[] roleIds_ = roleIds.split(","); 
		//添加当前权限
		List<SysRoleApplication> sysRoleApplications = new ArrayList<SysRoleApplication>();
		for(String roleId : roleIds_) {
			if(isSuper(roleId)) { //超级管理员权限角色不能修改
				disableSuper = true;
				continue;
			}
			//删除老权限
			SysRoleApplication sysRoleApplicationDel_ = new SysRoleApplication();
			sysRoleApplicationDel_.setRoleId(roleId);
			sysRoleApplicationService.delete(sysRoleApplicationDel_);
			
			int now = (int)new Date().getTime();
			for(String functionId : functionIds.split(",")) {
				if(StringUtils.isBlank(functionId)) {
					continue;
				}
				SysRoleApplication sysRoleApplication_ = new SysRoleApplication();
				sysRoleApplication_.setId(UUIDFactory.getUUID());
				sysRoleApplication_.setCreateTime(now);
				sysRoleApplication_.setRoleId(roleId);
				sysRoleApplication_.setFunctionId(functionId);
				sysRoleApplications.add(sysRoleApplication_);
				success = true;
			}
		}
		if(disableSuper && !success) {
			return ApiResponse.fail(ResultFlagType.BAN_SUPER_ADMIN_ROLE);
		}
		sysRoleApplicationService.save(sysRoleApplications);
		return ApiResponse.success(true);
	}
	
	/**
	 * 角色禁用
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping(value = { "disable" }, method = { RequestMethod.POST })
	public ApiResponse disable(@Validated(Id.class) SysRole role) {
		AbstractSysUser currentUser = getCurrentUser();
		boolean disableSuper = false;
		boolean success = false;
		for(String roleId : role.getId().split(",")) {
			if(isSuper(roleId)) { //超级管理员权限角色不能修改
				disableSuper = true;
				continue;
			}
			if(StringUtils.isBlank(roleId)) {
				continue;
			}
			SysRole role_ = new SysRole();
			role_.setId(roleId);
			role_.setDpStatus(DpStatus.INVALID.getCode());
			role_.setModifierName(currentUser.getName());
			role_.setModifier(currentUser.getId());
			success = true;
			sysRoleService.saveUpdateAndDelete(role_, OperateType.edit);
		}
		if(disableSuper && !success) {
			return ApiResponse.fail(ResultFlagType.BAN_SUPER_ADMIN_ROLE);
		}
		return ApiResponse.success(true);
	}
	
	/**
	 * 角色激活
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping(value = { "enable" }, method = { RequestMethod.POST })
	public ApiResponse enable(@Validated(Id.class) SysRole role) {
		AbstractSysUser currentUser = getCurrentUser();
		for(String roleId : role.getId().split(",")) {
			if(StringUtils.isBlank(roleId)) {
				continue;
			}
			SysRole role_ = new SysRole();
			role_.setId(roleId);
			role_.setDpStatus(DpStatus.NORMAL.getCode());
			role_.setModifierName(currentUser.getName());
			role_.setModifier(currentUser.getId());
			sysRoleService.saveUpdateAndDelete(role_, OperateType.edit);
		}
		return ApiResponse.success(true);
	}

}
